package com.notetool.util.tokenparser.semantic;

import com.notetool.util.tokenparser.Token;
import com.notetool.util.tokenparser.TokenList;
import com.notetool.util.tokenparser.syntax.Model;

public class MatchingTokensRestriction extends ParsingRestriction
{
    
    ////////////////////
    // Members
    private Model firstModel;
    private Model secondModel;

    ////////////////////
    // Constructors
    public MatchingTokensRestriction (Model first, Model second)
    {
        firstModel = first;
        secondModel = second;
    }
    
    ////////////////////
    // ParsingRestriction implementation
    public void checkRestriction (TokenList list) throws ParserSemanticException
    {
        if (list == null)
            return;
        
        int count = 0;
        ParserSemanticException ex = new ParserSemanticException ("Token without a matching token found.");
        
        // Loop through tokens
        Token curToken = list.getFirst ();
        while (curToken != null)
        {
            // If the token's model is our firstModel, we increment
            if (curToken.getModel () == firstModel)
                count += 1;
            
            // If the token's model is our secondToken, we decrement
            if (curToken.getModel () == secondModel)
                count -= 1;
            
            if (count < 0)
                throw ex;
            
            curToken = curToken.getNext ();
        }
        
        if (count != 0)
            throw ex;
    }
    
}
